//
//  MSUserAccountInfoModel.swift
//  SwiftWeibo
//
//  Created by 牟松 on 16/8/15.
//  Copyright © 2016年 DoNews. All rights reserved.
//

import UIKit
import YYModel

private let userAccountFileName: String = "userAccount.json"

class MSUserAccountInfoModel: NSObject {

    
    /** accesstoken */
    var access_token: String?
    /** access_token的生命周期 */
    var expires_in: TimeInterval = 0{
        didSet{
            expirseDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /** expirseDate 过期日期*/
    var expirseDate:Date?
    
    /** uid的生命周期 */
    var uid:String?
    /** 用户名 */
    var name: String?
    /** 头像，高清原图 */
    var avatar_hd: String?
    
    static let shared:MSUserAccountInfoModel = {
        let instance = MSUserAccountInfoModel()
        return instance
    }()
    
    
    var userLogin: Bool {
        return MSUserAccountInfoModel.shared.access_token != nil
    }
    

    override var description: String{
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        
        let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let filePath = (documentPath! as NSString).appendingPathComponent(userAccountFileName)
        
        print("filePath========\(filePath)")
        
        guard let data = NSData(contentsOfFile: filePath),
            let dict = try? JSONSerialization.jsonObject(with: (data as Data), options: []) as? [String: AnyObject]
            else {
                return
        }
        
        yy_modelSet(with: dict ?? [:])
        
        if expirseDate?.compare(Date()) != .orderedDescending {
            access_token = nil
            uid = nil
            
            try? FileManager.default.removeItem(atPath: filePath)
        }
        
        
        
        
    }
    
    func saveUserAccountInfo() {
        
        var dict = (self.yy_modelToJSONObject() as? [String: AnyObject]) ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let filePath = (documentPath! as NSString).appendingPathComponent(userAccountFileName)
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
            else{
                return
        }
        
        (data as NSData).write(toFile: filePath, atomically: true)
        
        
    }
    
    
}
